package com.service.proxy;


import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.w3c.dom.Element;

import com.pub.dbo.domain.Proxy;
import com.pub.dbo.impl.ProxyImpl;
import com.pub.util.XMLUtils;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;



public class ProxyHttpHandler implements HttpHandler
{
	private static Logger logger;
	
	private ProxyImpl proxyImpl;
	
	static
	{
		logger = Logger.getLogger (ProxyHttpHandler.class.getName());
	}

	/**
	 * 
	 */
	public ProxyHttpHandler(String DBTag) 
	{
		proxyImpl = new ProxyImpl(DBTag);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handle(HttpExchange httpExchange) throws IOException 
	{
		boolean isValidOut = false;
		
		Map<String, Object> params = (Map<String, Object>)httpExchange.getAttribute("parameters"); 
//		logger.info("params----------- = " + params.toString());
		
		OutputStream out = httpExchange.getResponseBody();
         
		Headers headers = httpExchange.getResponseHeaders();  
        headers.set("Content-Type", "text/xml");
        headers.set("Server", "ProxyHttpServer 0.1");

        httpExchange.sendResponseHeaders(200, 0);

		XMLUtils xu = new XMLUtils();

		try {
//			int page 			= 1;
//			int pageSize		= 20;
			int limit			= 200;
			
//			if(params.containsKey("page") && ((String)params.get("page")).matches("[\\d]+")){
//				page = Integer.parseInt((String)params.get("page"));
//			}
//			
//			if(params.containsKey("pageSize") && ((String)params.get("pageSize")).matches("[\\d]+")){
//				pageSize = Integer.parseInt((String)params.get("pageSize"));
//			}
			
			
			if(params.containsKey("limit") && ((String)params.get("limit")).matches("[\\d]+")){
				limit = Integer.parseInt((String)params.get("limit"));
			}
			
			xu.newXMLDocument();
//			xu.getDoc().createComment("this is valid proxy list.");
			
			xu.addComment("this is valid proxy list.");
			xu.addComment(" L: one proxy. ");
			xu.addComment(" i: proxy ip ");
			xu.addComment(" p: proxy port ");
			xu.addComment(" c: proxy country ");
			xu.addComment(" a: proxy anonymous ");
			xu.addComment(" r: proxy rating ");
			
			Vector<Proxy> proxyList = proxyImpl.getList(limit);
			
			Element rootElement = xu.createRootElement("proxy");

			rootElement.setAttribute("total", Integer.toString(proxyList.size()));
//			rootElement.setAttribute("page", Integer.toString(page));
//			rootElement.setAttribute("pagesize", Integer.toString(pageSize));
			
			for(Proxy proxy : proxyList){
				Element dataElement = xu.addElement(rootElement, "L");
				xu.addElement(dataElement, "i", proxy.getIP());
				xu.addElement(dataElement, "p", Integer.toString(proxy.getPort()));
				xu.addElement(dataElement, "c", proxy.getCountry());
				xu.addElement(dataElement, "a", proxy.getAnonymous());
				xu.addElement(dataElement, "r", Integer.toString(proxy.getRating()));
			}
		
			xu.buildXml(out);
			
			isValidOut = true;
		} catch (Exception e) {
			logger.info("fetch index data error. Exception : " + e.getMessage());
			e.printStackTrace();
		}
		
		if(!isValidOut){
			try {
				logger.info("invalid query parameter.");
		        httpExchange.sendResponseHeaders(404, 0);

				xu.newXMLDocument();
				
				Element rootElement = xu.createRootElement("proxy");
				xu.addElement(rootElement, "error", "invalid parameter.");
				
				xu.buildXml(out);
			} catch (Exception e) {
				logger.info("default out xml error. Exception : " + e.getMessage());
				e.printStackTrace();
			}
		}
		
        out.flush();  
        out.close();  

	}
	
}